import torch
import torch.nn as nn
import torch.optim as optim
import scipy.io
import numpy as np
import os
import matplotlib.pyplot as plt

# 数据读取 三维卷积可运行
data_folder1 = "dync"
file_prefix = "spatial_correlation_"
file_extension = ".mat"

# 参数
m = 50  # 时间点数
k = 481  # 丰度矩阵的维度
K_nonzero = 20  # 稀疏性要求
lambda_sparsity = 0.1  # 稀疏正则化系数
epochs = 1000
learning_rate = 0.001

# 初始化输入矩阵
result_matrix = np.zeros((8, 8, m), dtype=np.complex64)  # 确保支持复数

# 读取前 m 个文件
for i in range(1, m + 1):
    fname2 = os.path.join(data_folder1, f"{file_prefix}{i}{file_extension}")
    if os.path.exists(fname2):
        mat2 = scipy.io.loadmat(fname2)
        if "p" in mat2:
            Y = mat2["p"]
            if Y.size == 64:
                Y_reshaped = Y.reshape(8, 8)
                result_matrix[:, :, i - 1] = Y_reshaped
            else:
                print(f"Shape of 'p' in {fname2} is not compatible for reshaping to 8x8.")
        else:
            print(f"'p' not found in {fname2}")
    else:
        print(f"File not found: {fname2}")

# 分离实部和虚部
Y_real = torch.from_numpy(np.real(result_matrix)).float().cuda()
Y_imag = torch.from_numpy(np.imag(result_matrix)).float().cuda()
Y_combined = torch.stack((Y_real, Y_imag), dim=0).unsqueeze(0)  # 形状为 (1, 2, 8, 8, m)

# 读取端元矩阵 D
fname4 = "Data/DC1/phasecha.mat"
mat4 = scipy.io.loadmat(fname4)
D = mat4["phasecha"]
if D.shape[0] == 64:
    D1 = D.reshape(8, 8, -1)
else:
    raise ValueError("The number of rows in D is not compatible with 8x8 reshaping.")
D_real = torch.from_numpy(np.real(D1)).float().cuda()
D_imag = torch.from_numpy(np.imag(D1)).float().cuda()
D_combined = torch.stack((D_real, D_imag), dim=0)  # 形状为 (2, 8, 8, k)

# 定义模型
class Conv3DAutoencoder(nn.Module):
    def __init__(self, k, D, time_steps):
        super(Conv3DAutoencoder, self).__init__()
        self.encoder = nn.Sequential(
            nn.Conv3d(2, 16, kernel_size=(3, 3, 3), stride=1, padding=1),
            nn.LeakyReLU(0.1),
            nn.Conv3d(16, 32, kernel_size=(3, 3, 3), stride=2, padding=1),
            nn.LeakyReLU(0.1),
            nn.Flatten(),
            nn.Linear(32 * 4 * 4 * (time_steps // 2), k * time_steps),
            nn.ReLU()
        )
        self.k = k
        self.time_steps = time_steps
        self.register_buffer('D', D)

    def forward(self, Y):
        batch_size = Y.size(0)
        X_flat = self.encoder(Y)  # 输出 (batch, k * time_steps)
        X = X_flat.view(batch_size, self.k, self.time_steps)  # 转换为 (batch, k, time_steps)

        # 稀疏化
        topk_values, topk_indices = torch.topk(X, K_nonzero, dim=1)
        mask = torch.zeros_like(X)
        mask.scatter_(1, topk_indices, topk_values)
        X = mask

        # 归一化
        X = X / (torch.sum(X, dim=1, keepdim=True) + 1e-8)

        # 重建
        D_real, D_imag = self.D[0], self.D[1]
        Y_reconstructed_real = torch.einsum("bkt,ijk->bijt", X, D_real)
        Y_reconstructed_imag = torch.einsum("bkt,ijk->bijt", X, D_imag)
        Y_reconstructed = torch.stack((Y_reconstructed_real, Y_reconstructed_imag), dim=1)
        return Y_reconstructed, X

# 模型初始化
model = Conv3DAutoencoder(k=k, D=D_combined, time_steps=m).cuda()

# 定义损失函数和优化器
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

# 训练
loss_values = []
for epoch in range(epochs):
    model.train()
    optimizer.zero_grad()

    # 前向传播
    Y_reconstructed, X = model(Y_combined)
    mse_loss_real = criterion(Y_reconstructed[:, 0], Y_combined[:, 0])
    mse_loss_imag = criterion(Y_reconstructed[:, 1], Y_combined[:, 1])
    mse_loss = mse_loss_real + mse_loss_imag

    # 稀疏性损失
    target_sparsity = K_nonzero / k
    actual_sparsity = (X > 0).float().mean(dim=1)
    sparsity_loss = ((actual_sparsity - target_sparsity) ** 2).mean()

    # 总损失
    loss = mse_loss + lambda_sparsity * sparsity_loss
    loss.backward()
    optimizer.step()

    loss_values.append(loss.item())

    # 打印日志
    if (epoch + 1) % 100 == 0:
        print(f"Epoch [{epoch + 1}/{epochs}], Total Loss: {loss.item():.4f}, "
              f"MSE Loss: {mse_loss.item():.4f}, Sparsity Loss: {sparsity_loss.item():.4f}")

# 绘制损失曲线
plt.plot(range(epochs), loss_values)
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('Loss Curve')
plt.show()

# 测试
model.eval()
with torch.no_grad():
    Y_reconstructed, X = model(Y_combined)
    print("Reconstruction completed.")
